import { defineStore } from 'pinia'

// JWT令牌浏览器端的持久化
export const getToken = () => localStorage.getItem('jwt_token')
export const setToken = (token) => localStorage.setItem('jwt_token', token)
export const removeToken = () => localStorage.removeItem('jwt_token')


// 前端用户登录状态的统一管理，基于pinia实现
export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,                  // 用户名
    token: getToken() || null,   // token
    roles: [],                   // 用户所有角色
    currentRole: null            // 当前选中的角色
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    hasRole: (state) => (role) => state.roles.includes(role)
  },

  actions: {
    async login(credentials) { // 登录操作
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credentials)
      })
      if (!res.ok) throw new Error(`HTTP 错误：${res.status}`)
      const result = await res.json()
      if (result.code !== 0) throw new Error(result.msg)
      this.loginSuccess(result.data) // 登录成功则更新前端用户状态
      return result.data // 方便组件拿到数据
    },
    async checkLoginStatus(){ // 从服务端获取用户认证状态，即检查JWT是否还有效
      const token = getToken()
      if (!token) throw new Error('未登录')
      const res = await fetch('/api/auth/status', {
        method: 'GET',
        headers: {
          ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
          'Content-Type': 'application/json'
        }
      })
      if (!res.ok) throw new Error(`HTTP 错误：${res.status}`)
      const result = await res.json()
      if (result.code !== 0) throw new Error('认证失败')
      this.loginSuccess(result.data) // 认证状态有效，更新前端用户状态
      return result.data // 用户信息
    },
    async loginSuccess(userInfo) {
      this.user = userInfo.username
      this.token = userInfo.token
      this.roles = userInfo.roles || []
      this.currentRole = this.roles.length > 0 ? this.roles[0] : null
      setToken(this.token)
    },
    async logout() {
      try {
        const token = getToken()
        if (!token) {
          // 没登录直接清理状态，避免报错阻断流程
          this.clearState()
          return
        }
        const res = await fetch('/api/auth/logout', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        })
        if (!res.ok) throw new Error(`HTTP 错误：${res.status}`)
        const result = await res.json()
        if (result.code !== 0) throw new Error('退出失败')
        this.clearState()
      } catch (err) {
        console.error('退出登录失败:', err)
      }
    },
    clearState() {
      this.user = null
      this.token = null
      this.roles = []
      this.currentRole = null
      removeToken()
    },
    setCurrentRole(role) {
      if (this.roles.includes(role)) {
        this.currentRole = role
      } else {
        console.warn(`角色 ${role} 不存在于当前用户的角色列表`)
      }
    }
  }
})

